<?php

namespace app\model\v1\recruit;

use app\model\user\User;
use crmeb\traits\ModelTrait;
use think\Exception;
use think\Model;

class RecruitJob extends Model
{

	use ModelTrait;

	protected $updateTime = false;
	protected $createTime = false;

	protected $hidden = [
		//    'create_time','update_time','delete_time'
	];


	public function industry ()
	{
		return $this->hasOne ('recruit_industry','id','industry_id');
	}

	public function  company ()
	{
		return $this->hasOne ('recruit_company','id','f_id');
	}
	public function  Collection ()
	{
		return $this->hasOne ('recruit_Collection','job_id','id');
	}

	public function kefu ()
	{
		return $this->hasOne (User::class,'uid','kefu_id');
	}


	/**
	 * 求职招聘后台 - 获取岗位管理列表
	 * @param $param
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public static function getRecruitJobList($param = [])
	{
		$data["data"] = self::field("id,position,f_id,industry_id,experience_required,salary_min,salary_max,job_requirements,u_phone,benefits,
            phone_count,chat_count,status,phone_count_use,chat_count_use,created_at,job_category,kefu_id,
            case when status=1 then '上架'
            when status =2 then '下架'
            end as status_text
            ")
			->with([
				'company'=> function($query) {
					$query->field ('id,name,introduction,contact_phone');
				},
				'industry'=> function($query) {
					$query->field ('id,industry_name');
				},
				'kefu'=> function($query) {
					$query->field ('uid,nickname,phone');
				}
			])
			->whereNULL("delete_at")
			->where(function ($query) use ($param){
				if(!empty($param["position"])) $query->where("position", 'like', '%'.$param["position"].'%');   //根据岗位名称搜索
				if(!empty($param["industry_id"])) $query->where("industry_id", $param["industry_id"]);   //根据行业id搜索
				if(!empty($param["experience_required"])) $query->where("experience_required", $param["experience_required"]);   //根据工作经验搜索
				if(!empty($param["status"])) $query->where("status", $param["status"]);   //根据状态搜索
			})
			->page($param["page"], $param["limit"])
			->select()
			->toArray();

		$data["count"] = self::whereNULL("delete_at")
			->where(function ($query) use ($param){
				if(!empty($param["position"])) $query->where("position", 'like', '%'.$param["position"].'%');   //根据岗位名称搜索
				if(!empty($param["industry_id"])) $query->where("industry_id", $param["industry_id"]);   //根据行业id搜索
				if(!empty($param["experience_required"])) $query->where("experience_required", $param["experience_required"]);   //根据工作经验搜索
				if(!empty($param["status"])) $query->where("status", $param["status"]);   //根据状态搜索
			})
			->count();

		return $data;

	}


	/**
	 * 求职招聘后台 - 获取岗位管理列表 - 查看
	 * @param $param
	 * @return RecruitJob|array|mixed|Model|null
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public static function getRecruitJobDetail($param = [])
	{
		return self::field("*,
            case when status=1 then '上架'
            when status =2 then '下架'
            end as status_text
            ")
			->with([
				'company'=> function($query) {
					$query->field ('id,name,introduction');
				},
				'industry'=> function($query) {
					$query->field ('id,industry_name');
				}
			])
			->where("id", $param["id"])
			->find();
	}
	public static function getRecruitJobDetail1($param = [])
	{
		return self::field("*,
            case when status=1 then '上架'
            when status =2 then '下架'
            end as status_text
            ")
			->with([
				'company'=> function($query) {
					$query->field ('id,name,introduction');
				},
				'industry'=> function($query) {
					$query->field ('id,industry_name');
				}
			])
			->where("id",'in', $param)
			->select();
	}

	/**
	 * 求职招聘后台 - 获取岗位管理列表 - 启用禁用
	 * @param $param
	 * @return string
	 */
	public static function enableRecruitJob($param = [])
	{
		$status = self::where("id", $param['id'])->value("status");
		$msg = '';
		if($status == 1){   //1启用 2禁用
			$enable = 2;
			$msg = "禁用成功";
		}else{
			$enable = 1;
			$msg = "启用成功";
		}
		self::where("id", $param['id'])->update(['status' => $enable]);
		return $msg;
	}


	public static function updateRecruitJob($param = [])
	{
		$update["updated_at"] = date("Y-m-d H:i:s");  //更新时间
		if(!empty($param["position"]))      $update["position"] = $param["position"];  //职位名称
		if(!empty($param["industry_id"]))   $update["industry_id"] = $param["industry_id"]; //行业
		if(!empty($param["job_category"]))  $update["job_category"] = $param["job_category"]; //职位类型
		if(!empty($param["salary_max"]))    $update["salary_max"] = $param["salary_max"]; //薪资最高
		if(!empty($param["salary_min"]))    $update["salary_min"] = $param["salary_min"]; //薪资最低
		if(!empty($param["phone_count"]))   $update["phone_count"] = $param["phone_count"]; //主动打电话次数
		if(!empty($param["chat_count"]))    $update["chat_count"] = $param["chat_count"]; //主动聊天次数

		return self::where("id", $param["id"])->update($update);
	}



	/**
	 * top区域搜索
	 * @param $param
	 * @return array
	 */
	public static function getRecruitSearchList($param = [])
	{
		if($param["search_type"] == 1) {
			// 审核通过的数据
			$jobs['data'] = RecruitJob::whereNull("delete_at")
				->field('*')
				->where(function ($query) use ($param){
					if (!empty($param['keyword'])){
						$query->where("position",'like', '%'.$param['keyword'].'%');
					}else{
						$query->where("position",'like', '');
					}
				})->where("status", 1)
				->with(['company'=> function($query) {
					$query->field('*');
				}])
				->order("id", "desc")
				->page($param['page'], $param['limit'])
				->select()
				->each(function (&$item) {
					$item['salary_range'] = $item['salary_min'] . 'K-' . $item['salary_max'] . 'K';
				})
				->toArray();
			$jobs['count'] = RecruitJob::whereNull("delete_at")
				->field('id,u_id,f_id,position,industry_id,salary_min,salary_max,city_name,district_name,benefits')
				->where(function ($query) use ($param){
					if (!empty($param['keyword'])){
						$query->where("position",'like', '%'.$param['keyword'].'%');
					}else{
						$query->where("position",'like', '');
					}
				})->where("status", 1)
				->count();
			return $jobs;

		}else{
			$data['data'] = RecruitCompany::whereNull("delete_at")
				->field('*')
				->where(function ($query) use ($param){
					if (!empty($param['keyword'])){
						$query->where("name",'like', '%'.$param['keyword'].'%')->whereOr("business_license_name",'like', '%'.$param['keyword'].'%');
					}else{
						$query->where("name",'like', '');
					}
				})->where("audit_state", 1)
				->select()->toArray();
			$data['count'] = RecruitCompany::whereNull("delete_at")
				->field('*')
				->where(function ($query) use ($param){
					if (!empty($param['keyword'])){
						$query->where("name",'like', '%'.$param['keyword'].'%')->whereOr("business_license_name",'like', '%'.$param['keyword'].'%');
					}else{
						$query->where("name",'like', '');
					}
				})->where("audit_state", 1)
				->count();
			return $data;
		}
	}



	public static function getUidJobIndustryIds($uid = '')
	{
		$find = self::whereNull("delete_at")->where("status", 1)->where("u_id", $uid)->column("industry_id") ?? [];
		if(!empty($find)) {
			$find = array_unique($find);
		}
		return $find;
	}



	public static function setPhoneChatCount($param = [])
	{
		$find = RecruitJob::where("id", $param['job_id'])->find();

		if($param["phone_type"] == 1){
			if($find["phone_count_use"] <= 0) Throw new Exception("打电话次数已用完！");
			return RecruitJob::where("id", $param['job_id'])->dec('phone_count_use', 1)->update();
		}
		if($param["phone_type"] == 2){
			if($find["chat_count_use"] <= 0) Throw new Exception("聊天次数已用完！");
			return RecruitJob::where("id", $param['job_id'])->dec('chat_count_use', 1)->update();
		}
	}
}